<template>
	<!-- <view class="container">
		<view class="authorize">
			<view class="store-info">
				<view class="header">
					<image class="image"
						:src="storeInfo && storeInfo.image_url ? storeInfo.image_url : '/static/default-logo.png'">
					</image>
				</view>
			</view>
			<view class="auth-title">申请获取以下权限</view>
			<view class="auth-subtitle">获得你的公开信息（昵称、头像等）</view>
			<view class="login-btn">
				<view class="button" :class="{ disabled }" @click="mnpLogin()">一键登录</view>
			</view>
			<view class="no-login-btn">
				<view class="button" @click="handleCancel()">暂不登录</view>
			</view>
		</view>
	</view> -->
	<view class="loginWrapper wd100 wrapperLayer bdbox colCen">
		<view class="logoImg">
			<u--image :src="logo" width="146rpx" height="146rpx"></u--image>
		</view>
		<!-- <view class="loginBtn rowCenCen" :class="{ disabled }" @click="mnpLogin">
			微信一键登录
		</view> -->
		<button  class="loginBtn rowCenCen" :class="{ disabled }" open-type="getPhoneNumber" @getphonenumber="mnpLogin">手机号登录</button>
	</view>
</template>

<script>
	import store from '@/store'
	import * as LoginApi from '@/api/login'
	import * as UploadApi from '@/api/upload'
	import AvatarImage from '@/components/avatar-image'
	import storage from '@/utils/storage';
	import {
		isEmpty
	} from '@/utils/util'
	import * as Verify from '@/utils/verify'

	export default {
		components: {
			AvatarImage
		},
		data() {
			return {
				logo:'',
				tempToken : "",
				// 是否需要填写用户昵称和头像
				isPersonal: true,

				// 微信小程序登录凭证 (code)
				// 提交到后端，用于换取openid
				code: '',
				// 按钮禁用
				disabled: false,
				// 头像路径 (用于显示)
				avatarUrl: '',
				// 临时图片 (用于上传)
				tempFile: undefined,
				// 表单数据
				form: {
					avatar: null,
					nickname: ''
				},
			}
		},

		created() {
			let baseInfo = storage.get('baseInfo');
			this.logo = baseInfo.website.shop_logo
		},

		methods: {

			/**
			 * 请求后端是否需要填写昵称头像 (微信小程序端)
			 *  - 条件1: 后台开启了填写微信头像和昵称
			 *  - 条件2: 用户首次注册或者已注册但未填写过信息
			 */
			async mnpLogin(e) {
				const app = this
				// console.log(await app.getCode());
				// console.log(e.detail.code);
				// return
				LoginApi.loginMpWx({
						code: await app.getCode(),
						phone_code:e.detail.code,
						refereeId : uni.getStorageSync('refereeId')
					})
					.then(result => {
						if(result.data.is_new_user == 0){
							// console.log(333);
							this.onAuthSuccessTwo(result.data);
						}else{
							// console.log(444);
							storage.set('tempToken',result.data.token)
							store.commit('SET_TOKEN', result.data.token)
							uni.navigateTo({
								url:"/pages/login/mp-weixin-two"
							})
						}
					})
			},

			// 获取code
			// https://developers.weixin.qq.com/miniprogram/dev/api/open-api/login/wx.login.html
			getCode() {
				return new Promise((resolve, reject) => {
					uni.login({
						provider: 'weixin',
						success({
							code
						}) {
							console.log('code', code)
							resolve(code)
						},
						fail: reject
					})
				})
			},

			// 绑定昵称输入框 (用于微信小程序端快速填写昵称能力)
			onInputNickName({
				detail
			}) {
				console.log(detail)
				if (detail.value) {
					this.form.nickname = detail.value
				}
			},

		
			// 一键登录按钮点击事件
			handleLogin() {
				const app = this
				wx.canIUse('getUserProfile') && wx.getUserProfile({
					lang: 'zh_CN',
					desc: '获取用户相关信息',
					success({
						userInfo
					}) {
						console.log('用户同意了授权')
						console.log('userInfo：', userInfo)
						// 授权成功事件
						app.onAuthSuccess({})
					},
					fail() {
						console.log('用户拒绝了授权')
					}
				})
			},

			async onAuthSuccessTwo(userInfo) {
				const app = this
				if (app.disabled === true) {
					return
				}
				// 按钮禁用
				app.disabled = true
				uni.showLoading({
					title: "登陆中"
				})
				store.dispatch('LoginMpWx', userInfo)
					.then(result => {
						uni.hideLoading()
						// 一键登录成功
						app.$toast("登录成功")
						// 跳转回原页面
						setTimeout(() => uni.navigateBack(), 2000)
					})
					.catch(err => {
						// 按钮可用
						app.disabled = false
						uni.hideLoading()
						const resultData = err.result.data
						// 显示错误信息
						if (isEmpty(resultData)) {
							app.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
						// 判断还需绑定手机号
						if (resultData.isBindMobile) {
							app.onEmitSuccess(userInfo)
						}
					})
			},
			async onAuthSuccess(userInfo) {
				const app = this
				if (app.disabled === true) {
					return
				}
				// 按钮禁用
				app.disabled = true
				uni.showLoading({
					title: "登陆中"
				})
				console.log(111)
				store.dispatch('updateUser', {
					  nickname: app.form.nickname,
					  avatar: app.form.avatar,
					  refereeId: store.getters.refereeId
					})
					.then(result => {
						// 一键登录成功
						app.$toast("登录成功")
						// 跳转回原页面
						uni.hideLoading()
						setTimeout(() => uni.navigateBack(), 2000)
					})
					.catch(err => {
						// 按钮可用
						app.disabled = false
						uni.hideLoading()
						const resultData = err.result.data
						// 显示错误信息
						if (isEmpty(resultData)) {
							app.$toast(err.result.message)
						}
						// 跳转回原页面
						if (resultData.isBack) {
							setTimeout(() => app.onNavigateBack(1), 2000)
						}
						// 判断还需绑定手机号
						if (resultData.isBindMobile) {
							app.onEmitSuccess(userInfo)
						}
					})
			},

			// 将oauth提交给父级
			// 这里要重新获取code, 因为上一次获取的code不能复用(会报错)
			async onEmitSuccess(userInfo) {
				const app = this
				app.$emit('success', {
					oauth: 'MP-WEIXIN', // 第三方登录类型: MP-WEIXIN
					code: await app.getCode(), // 微信登录的code, 用于换取openid
					userInfo // 微信用户信息
				})
			},

			/**
			 * 暂不登录
			 */
			handleCancel() {
				// 跳转回原页面
				this.onNavigateBack()
			},

			/**
			 * 登录成功-跳转回原页面
			 */
			onNavigateBack(delta = 1) {
				const pages = getCurrentPages()
				if (pages.length > 1) {
					uni.navigateBack({
						delta: Number(delta || 1)
					})
				} else {
					this.$navTo('pages/index/index')
				}
			}

		}
	}
</script>

<style lang="scss" scoped>
	.loginWrapper {
		width: 100%;
		min-height: 100vh;
		background-color: #fff;
	
		.logoImg {
			margin-top: 170rpx;
		}
	
		.loginBtn {
			width: 608rpx;
			height: 100rpx;
			background: #F65A45;
			border-radius: 50rpx;
			font-size: 32rpx;
			font-weight: bold;
			color: #FFFFFF;
			margin-top: 130rpx;
		}
		
	}
</style>